// 获取结算清单商品
(function() {

	if (!localStorage.getItem('token')) {
		alert('非法登录');
		location.href = 'index.html';
		return;
	};

	let oOrderListContent = document.querySelector('.order-list-content');
	let oNewAdd = document.querySelector('.new-add');
	let oNewAddressContent = document.querySelector('.new-address-content');
	
	// 判断是否需要新地址
	oNewAdd.onchange = function() {
		this.checked ? `${oNewAddressContent.style.display = 'block'}` : `${oNewAddressContent.style.display = 'none'}`;
	};


	yzb.ajax({
		method: 'post',
		url: BASE_URL + '/api_settlement',
		data: {
			status: 'getsettlement',
			userId: localStorage.getItem('token')
		},
		success(res) {
			if (res.code != 0) {
				console.log(res);
				return;
			};

			// dom
			let str = '';
			res.data.forEach(item => {
				str += `
				<div class="order-list">
					<div>
						<img src="${item.goods_thumb}" alt="" />
						<span>${item.goods_name}</span>
					</div>
					<div>
						<span>${item.goods_number}</span>
						<span>$${item.price}</span>
					</div>
				</div>
				`;
			});
			// 添加至页面
			oOrderListContent.innerHTML = str;
		}
	})

	// 地址列表容器元素
	let oOrAddItems = document.querySelector('.orAdd-items');
	// 新地址元素
	let oConsigneeNameDom = document.querySelector('.consignee-name');
	let oStreetDom = document.querySelector('.street');
	let oTelDom = document.querySelector('.tel');
	let oSaveBtn = document.querySelector('.save-btn');

	let nowProvince = '';
	let nowCity = '';
	let nowTown = '';
	let nowEditAddressId = '';
	let lockAddress = false;

	// 默认调用地址列表
	getAddressListData();

	// 获取当前用户地址
	function getAddressListData() {

		yzb.ajax({
			method: 'post',
			url: BASE_URL + '/api_address',
			data: {
				status: 'getAddress',
				userId: localStorage.getItem('token')
			},
			success(res) {
				if (res.code != 0) {
					console.log(res);
					return;
				};
				// 组装
				if (res.data.length == 0) {
					oOrAddItems.innerHTML = '快去添加收货地址吧~~~';
					return;
				};

				// 调用渲染方法
				renderAddressList(res.data);
			},
		});

	};

	// 渲染地址列表方法
	function renderAddressList(data) {

		// 整理数据结构
		let newArr = [...data];
		newArr.forEach((item, index) => {
			if (item.isDefault == true) {
				newArr.unshift(newArr.splice(index, 1)[0]);
			};
		});

		let str = '';
		newArr.forEach(item => {
			str += `
			<li address-id="${item.address_id}" class="list  ${item.isActive ? 'isActive' : ''}">
				<div>
					<p><span>${item.takename}</span><span>${item.tel}</span></p>
					<p>${item.province} ${item.city} ${item.district}</p>
					<p>${item.streetname}</p>
				</div>
				<div>
				  <p class="set-default ${item.isDefault ? 'isDefault' : ''}" address-id="${item.address_id}">${item.isDefault ? '默认地址' :'设为默认'}</p>
				
					<p><span class="edit-address" address-id="${item.address_id}">编辑</span><span class="del-address" address-id="${item.address_id}">删除</span></p>
				</div>
			</li>
			`;
		});
		// 添加到页面
		oOrAddItems.innerHTML = str;
		// 开锁
		lockAddress = false;

		let aList = document.querySelectorAll('.orAdd-items .list');
		let aSetDefault = document.querySelectorAll('.orAdd-items .set-default');
		let aDelAddress = document.querySelectorAll('.orAdd-items .del-address');
		let aEditAddress = document.querySelectorAll('.orAdd-items .edit-address');

		// 默认地址按钮


		// 遍历监听点击设置为当前收货地址
		aList.forEach(item => {
			item.onclick = function() {
				// 请求后台
				yzb.ajax({
					method: 'post',
					url: BASE_URL + '/api_address',
					data: {
						status: 'activeAddress',
						userId: localStorage.getItem('token'),
						addressId: this.getAttribute('address-id')
					},
					success: (res) => {
						if (res.code != 0) {
							console.log(res);
							return;
						};

						// 操作dom元素
						aList.forEach(item => {
							item.classList.remove('isActive');
						});
						this.classList.add('isActive');
					}
				});
			};
		});
		// 批量监听 设置为默认地址
		aSetDefault.forEach(item => {
			item.onclick = function(e) {
				// 阻止冒泡
				e.stopPropagation();
				// 请求后台
				yzb.ajax({
					method: 'post',
					url: BASE_URL + '/api_address',
					data: {
						status: 'defaultAddress',
						userId: localStorage.getItem('token'),
						addressId: this.getAttribute('address-id')
					},
					success: (res) => {
						if (res.code != 0) {
							console.log(res);
							return;
						};

						// 操作dom元素
						aSetDefault.forEach(item => {
							item.classList.remove('isDefault');
						});
						this.classList.add('isDefault');
						oOrAddItems.insertBefore(this.parentNode.parentNode, document.querySelectorAll(
							'.orAdd-items .list')[0]);
					}
				});
			};
		});

		// 批量监听删除
		aDelAddress.forEach(item => {
			item.onclick = function() {
				// 请求后台
				yzb.ajax({
					method: 'post',
					url: BASE_URL + '/api_address',
					data: {
						status: 'deleteAddress',
						userId: localStorage.getItem('token'),
						addressId: this.getAttribute('address-id')
					},
					success: (res) => {
						if (res.code != 0) {
							console.log(res);
							return;
						};

						// 操作dom元素
						this.parentNode.parentNode.parentNode.remove();
					}
				});
			};
		});

		// 批量监听编辑
		aEditAddress.forEach(item => {
			item.onclick = function() {
				// 设置要编辑的地址
				nowEditAddressId = this.getAttribute('address-id');
				// 数据设置到表单中去
				newArr.forEach(item => {
					if (item.address_id == nowEditAddressId) {
						oConsigneeNameDom.value = item.takename;
						oStreetDom.value = item.streetname;
						oTelDom.value = item.tel;
					};
				});
			}
		})
	};


	// 获取省市区
	let oProvinceDom = document.querySelector('.province');
	let oCityDom = document.querySelector('.city');
	let oTownDom = document.querySelector('.town');

	// 点击保存地址 保存新地址 或 编辑地址
	oSaveBtn.onclick = function() {
		// 上锁
		if (lockAddress) return;
		lockAddress = true;
		// 验证
		if (oConsigneeNameDom.value == '' || oStreetDom.value == '') {
			alert('不能为空');
			return;
		};
		let re = /^1[3456789]\d{9}$/g;
		if (!re.test(oTelDom.value)) {
			alert('请输入正确的手机号');
			return;
		};

		// 验证是新增还是编辑
		// 要先保存新地址 再删除旧地址
		yzb.ajax({
			method: 'post',
			url: BASE_URL + '/api_address',
			data: {
				status: 'addAddress',
				userId: localStorage.getItem('token'),
				province: nowProvince,
				city: nowCity,
				district: nowTown,
				streetname: oStreetDom.value,
				takename: oConsigneeNameDom.value,
				tel: oTelDom.value,
			},
			success(res) {
				if (res.code != 0) {
					console.log(res);
					return;
				};

				// 验证
				if (nowEditAddressId) {
					// 删除旧地址
					yzb.ajax({
						method: 'post',
						url: BASE_URL + '/api_address',
						data: {
							status: 'deleteAddress',
							userId: localStorage.getItem('token'),
							addressId: nowEditAddressId,
						},
						success(res) {
							if (res.code != 0) {
								console.log(res);
								return;
							};
							// 清空表单元素
							oConsigneeNameDom.value = '';
							nowProvince.value = '';
							nowCity.value = '';
							nowTown.value = '';
							oStreetDom.value = '';
							oTelDom.value = '';
							// 把nowEditAddressId 设置为空
							nowEditAddressId = '';
							// 重新渲染
							getAddressListData();

						}
					})
				} else {
					// 多了一条数据 只要把它添加到渲染列表方法里去
					getAddressListData();
					// 清空表单元素
					oConsigneeNameDom.value = '';
					nowProvince.value = '';
					nowCity.value = '';
					nowTown.value = '';
					oStreetDom.value = '';
					oTelDom.value = '';
				}

			}
		});
	};




	// 默认调用省
	getProvince();

	// 请求省
	function getProvince() {
		yzb.ajax({
			url: BASE_URL + '/api_country',
			data: {},
			success(res) {
				if (res.code != 0) {
					console.log(res);
					return;
				};
				// dom
				let str = '<option value="">--请选择省--</option>';
				res.data.forEach(item => {
					str += `
				<option value="${item.name}">${item.name}</option>
				`;
				});
				// 添加到页面
				oProvinceDom.innerHTML = str;

				oProvinceDom.onchange = function() {
					nowProvince = this.value;
					// 调用城市数据
					getCity(this.value, oCityDom, '--请选择市--');
				}
			}
		})
	};

	// 请求城市
	function getCity(province, dom, strCity) {
		yzb.ajax({
			url: BASE_URL + '/api_country',
			data: {
				province
			},
			success(res) {
				if (res.code != 0) {
					console.log(res);
					return;
				};

				// 用来区分区数据
				let datas = res.data.area || res.data;

				// dom
				let str = '<option value="">' + strCity + '</option>';
				datas.forEach(item => {
					str += `
				<option value="${item.name}">${item.name}</option>
				`;
				});
				// 添加到页面
				dom.innerHTML = str;

				dom.onchange = function() {
					nowCity = this.value;
					// 调用区方法
					getTown(nowProvince, nowCity, oTownDom, '--请选择区--');
				}
			}
		})
	};

	// 请求区
	function getTown(province, city, dom, strTown) {
		yzb.ajax({
			url: BASE_URL + '/api_country',
			data: {
				province,
				city
			},
			success(res) {
				if (res.code != 0) {
					console.log(res);
					return;
				};
				// dom
				let str = '<option value="">' + strTown + '</option>';
				let dataTown = res.data.area || res.data;
				dataTown.forEach(item => {
					str += `
				<option value="${item.name}">${item.name}</option>
				`;
				});
				// 添加到页面
				dom.innerHTML = str;
				dom.onchange = function() {
					nowTown = this.value;
				};
			}
		})
	};

	// 点击结算
	let oSettleBtn = document.querySelector('.settle-btn');

	oSettleBtn.onclick = function() {
		// 验证选中地址
		// 验证有无商品
		// 获取总价

		// 请求支付地址
		yzb.ajax({
			method: 'post',
			url: BASE_URL + '/api_payment',
			data: {
				userId: localStorage.getItem('token'),
				orderId: new Date().getTime(),
				returnUrl: 'http://127.0.0.1:8848/%E8%89%AF%E4%BB%93/mypay.html',
				totalAmount: '123',
				subject: '标题',
				body: '订单详情'
			},
			success(res) {
				if (res.code != 0) {
					console.log(res);
					return;
				};
				// 获取支付地址成功
				location.href = res.data;
			}
		})
	}
})();